<?php
uses('sanitize');
class NewzController extends AppController {

	var $name = 'Newz';
	var $uses = null;
	var $helpers = array('Html', 'Javascript', 'Form');
	var $components = array('RequestHandler', 'Cookie');

	function beforeFilter() {
		if($this->Session->check('user')) {
			// user is logged in
		} else {
			// user is not logged in
	#		$this->Session->setFlash('You must be logged in to do that');
	#		$this->redirect(array('controller' => 'users', 'action' => 'login'));
#			$this->layout = 'ajax';
			$this->log('not logged in');
			$this->viewPath = 'users';
			$this->render('login');
#			$this->render('/users/login');
		}
	}
	
	function download($id) {
		if(empty($id)) {
			
		} else {
			$action = 'enqueuenewzbin';
			$this->setQueue(_HELLA_HOST_, _HELLA_PORT_, _HELLA_USERNAME_, _HELLA_PASSWORD_, $action, $id);
		}
	}
	
	
	function setQueue ($host, $port, $user, $passwd, $action, $id) {
		vendor('xmlrpc');
		 if ($id <> '')
		 	$f=new xmlrpcmsg($action, array(new xmlrpcval($id, "string")));
		 else
			$f=new xmlrpcmsg($action, "");
	         $c=new xmlrpc_client("", $host, $port);
	         $c->setCredentials($user,$passwd);
	         $c->setDebug(0);
	         $r=$c->send($f);
	         if(!$r->faultCode())
	         	//Got a valid result, decode into php variables
	                return php_xmlrpc_decode($r->value());
	         else {
	                //Got an error, print description
	                echo "Fault: ";
	                echo "Code: " . htmlspecialchars($r->faultCode())
	                	. " Reason '" . htmlspecialchars($r->faultString()) . "'<BR>";

	         }
	}

	public function search() {
		$this->layout = 'ajax';
		vendor('RSS');
		
		$uri = 'http://v3.newzbin.com/search/query/?area=-1&fpn=p&searchaction=Go&areadone=-1&feed=rss&q=' . urlencode($_REQUEST['keyword']);
		$this->log($uri);
		$rss = new XML_RSS($uri);

		$rss->parse();
		$this->set('keyword', $uri);
		$this->set('debug', $this->data);
#		$this->set('items', $rss->getItems());
		$items = $rss->getItems();
		foreach($items as &$item) {
			$dom  = new DOMDocument();
			$dom->loadXML($item['description']);
			$lis = $dom->getElementsByTagName('li');
			foreach($lis as $l) {
				$item['info'][] = $l->nodeValue;
				$this->log($l->nodeValue);
			}
		}
		$this->set('items', $items);
	}
/*
	public function search() {
		$this->layout = 'ajax';
	}
*/	
	function login(){
		
	}
	
	public function home() {
		
	}
}
?>